﻿using ce.autofac.extension;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NLog;
using System.Dynamic;

namespace learun.util
{
    /// </summary>
    public static class ContextHelper
    {


        public static string Userid()
        {
            return GetItem("userId").ToString();
        }

        public static string deptId()
        {
            return GetItem("deptId").ToString();
        }

        public static string deptName()
        {
            return GetItem("deptName").ToString();
        }

        /// <summary>
        /// 获取上下文值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static object GetItem(string key)
        {
            //ContextHelper.SetItem("account", Jresult.user_info.id.ToString());
            //ContextHelper.SetItem("userId", Jresult.user_info.id.ToString());
            //ContextHelper.SetItem("userName", Jresult.user_info.username);
            //ContextHelper.SetItem("deptId", Jresult.user_info.deptId);
            //ContextHelper.SetItem("deptName", Jresult.user_info.deptName);
            Logger _logger = LogManager.GetCurrentClassLogger();
            
            var accessor = IocManager.Instance.GetService<IHttpContextAccessor>();
            _logger.Log(NLog.LogLevel.Info, "IHttpContextAccessor"+ accessor.ToString());
            accessor.HttpContext.Items.TryGetValue(key, out object res);
            return res;
        }
        /// <summary>
        /// 设置上下文值
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void SetItem(string key, string value)
        {
            var accessor = IocManager.Instance.GetService<IHttpContextAccessor>();
            if (accessor.HttpContext.Items.ContainsKey(key))
            {
                accessor.HttpContext.Items.Remove(key);
            }
            accessor.HttpContext.Items.Add(key, value);
        }
        /// <summary>
        /// 移除上下文值
        /// </summary>
        /// <param name="key"></param>
        public static void RemoveItem(string key)
        {
            var accessor = IocManager.Instance.GetService<IHttpContextAccessor>();
            if (accessor.HttpContext.Items.ContainsKey(key))
            {
                accessor.HttpContext.Items.Remove(key);
            }

        }
    }
}
